package com.scut.wordskillerbackend.controller;

import com.scut.wordskillerbackend.dto.RespBean;
import com.scut.wordskillerbackend.po.User;
import com.scut.wordskillerbackend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public RespBean register(@RequestParam String username, @RequestParam String password) {
        User user = new User(username, password);
        boolean result;
        try {
            result = userService.register(user);
        } catch (Exception e) {
            return RespBean.unprocessable("注册失败" + e.getMessage());
        }
        if (result) {
            return RespBean.ok("注册成功", new HashMap<String, Object>() {
                {
                    put("token", user.getToken());
                }
            });
        }
        return RespBean.unprocessable("注册失败");
    }

    @PostMapping("/login")
    public RespBean login(@RequestParam String username, @RequestParam String password) {
        User user;
        User userLogin = new User(username, password);
        try {
            user = userService.login(userLogin);
        } catch (Exception e) {
            return RespBean.unprocessable("登录失败" + e.getMessage());
        }
        if (user != null) {
            return RespBean.ok("登录成功", new HashMap<String, Object>() {
                {
                    put("token", user.getToken());
                }
            });
        }
        return RespBean.unprocessable("登录失败");
    }

    @PutMapping("/update")
    public RespBean updateUser(@RequestParam String password,
                               @RequestHeader("Authorization") String authorization) {
        User user;
        try {
            user = userService.updateUser(password, authorization);
        } catch (Exception e) {
            return RespBean.unprocessable("密码修改失败" + e.getMessage());
        }
        if (user != null) {
            return RespBean.ok("密码修改成功", new HashMap<String, Object>() {
                {
                    put("token", user.getToken());
                }
            });
        }
        return RespBean.unprocessable("密码修改失败");
    }
}
